//
//  StatusLabel.m
//  Weibo
//
//  Created by Anasue on 10/4/15.
//  Copyright © 2015 vvusu. All rights reserved.
//

#define LinkBackgroundTag 999

#import "StatusLabel.h"
#import "Link.h"

@interface StatusLabel ()
@property (nonatomic, weak) UITextView *textView;
@property (nonatomic, strong) NSMutableArray *links;

@end

@implementation StatusLabel

- (NSMutableArray *)links
{
    if (_links == nil) {
        NSMutableArray *links = [NSMutableArray array];
        [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
            NSString *linkText = attrs[@"Link"];
            if (linkText == nil) return;
            Link *link = [[Link alloc]init];
            link.text = linkText;
            link.range = range;
            NSMutableArray *rects = [NSMutableArray array];
            self.textView.selectedRange = range;
            NSArray *selectRects = [self.textView selectionRectsForRange:self.textView.selectedTextRange];
            for (UITextSelectionRect *seletedRect in selectRects) {
                if (seletedRect.rect.size.width == 0 || seletedRect.rect.size.height == 0) continue;
                [rects addObject:seletedRect];
            }
            link.rects = rects;
            [links addObject:link];
        }];
        self.links = links;
    }
    return _links;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        UITextView *textView = [[UITextView alloc]init];
        textView.userInteractionEnabled = NO;
        textView.backgroundColor = [UIColor clearColor];
        textView.textContainerInset = UIEdgeInsetsMake(0, -5, 0, -5);
        textView.scrollEnabled = NO;
        textView.editable = NO;
        [self addSubview:textView];
        self.textView = textView;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.textView.frame = self.bounds;
}

- (void)setAttributedText:(NSMutableAttributedString *)attributedText
{
    _attributedText = attributedText;
    self.textView.attributedText = attributedText;
    self.links = nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:touch.view];
//    Log(@"%@",NSStringFromCGPoint(point));
    Link *touchingLink = [self touchLinkWithPoint:point];
    [self showBackgroundWithLink:touchingLink];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:touch.view];
    Link *touchingLink = [self touchLinkWithPoint:point];
    if (touchingLink) {
        [[NSNotificationCenter defaultCenter]postNotificationName:LinkDidSelectedNotification object:nil userInfo:@{@"Link":touchingLink.text}];
    }
    [self touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeAllLinks];
    });
}

- (Link *)touchLinkWithPoint:(CGPoint)point
{
    __block Link *touchingLink = nil;
    [self.links enumerateObjectsUsingBlock:^(Link *link, NSUInteger idx, BOOL * _Nonnull stop) {
        for (UITextSelectionRect *selectRect in link.rects) {
            if (CGRectContainsPoint(selectRect.rect, point)) {
                touchingLink = link;
                break;
            }
        }
    }];
    return touchingLink;
}

- (void)showBackgroundWithLink:(Link *)link
{ 
    for (UITextSelectionRect *selectRect in link.rects) {
        UIView *bg = [[UIView alloc]init];
        bg.backgroundColor = RandomColor;
        bg.frame = selectRect.rect;
        bg.layer.cornerRadius = 3;
        bg.tag = LinkBackgroundTag;
        [self insertSubview:bg atIndex:0];
    }
}

- (void)removeAllLinks
{
    for (UIView *view in self.subviews) {
        if (view.tag == LinkBackgroundTag) {
            [view removeFromSuperview];
        }
    }
}

@end
